/*
 * IJA2011, Board game "Clovece nezlob se"
 * grp108
 * Tomáš Mičiak,xmicia00
 * Andrej Martinák, xmarti51
 *
 */

package src.clovece.game;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import javax.swing.JDialog;
import src.clovece.ErrorDialog;
import src.clovece.LoginDialog;



/**
 *  Class handling connection to the game server
 */
public class Multiplayer {

     private GameInfo gameInfo = GameInfo.getGameInfoInstance();
     private String host = gameInfo.getHost();
     private int port = 19999;
     private InetAddress address = null;
     private Socket connection = null;
     private JDialog parent = null;

     public Multiplayer(JDialog parent)
    {
         this.parent = parent;

     }

     public Multiplayer()
    {}

     public void init()
    {
         try {
          this.address = InetAddress.getByName(this.host);
          this.connection = new Socket(this.address, this.port);
          gameInfo.setSocket(this.connection);
          BufferedReader rd = new BufferedReader(new InputStreamReader(this.connection.getInputStream()));
          gameInfo.setInputStream(rd);
        }
        catch (IOException f) {
          ErrorDialog ed = new ErrorDialog(this.parent,true, "Could not establish connection");
          ed.setVisible(true);
        }
          catch (Exception g) {
          System.out.println("Exception: " + g);
        }
     }


     public String readMessage (){

        String message = null;
        try {
              String str;
              //while (true) {
                str = gameInfo.getInputStream().readLine();
                
                //if (str.equals("END"))
                 //break;

                if (str != null)
                    message = str ;
                str = null;
               //}
        }
        catch (IOException f) {
          System.out.println("IOException: " + f);
        }
          catch (Exception g) {
          System.out.println("Exception: " + g);
        }

        return message;
    }

     public boolean login(String username, String pwd)
    {
         
         try {
          init();

          BufferedOutputStream bos = new BufferedOutputStream(this.gameInfo.getSocket().
              getOutputStream());

          OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

          String process = "Login:"+ username + "|" + pwd +  (char) 13;
          osw.write(process);
          osw.flush();

          BufferedInputStream bis = new BufferedInputStream(this.gameInfo.getSocket().
          getInputStream());


          InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");

          StringBuffer response = new StringBuffer();
          String stage = new String();
          String err = new String();

          int c;
          while ( (c = isr.read()) != 13)
            response.append( (char) c);

          response.append((char)30);

          char [] chars = response.toString().toCharArray();
          int i = 0;
          while (chars[i] != ':')
          {
              stage += chars[i];
              i++;
          }
          i++;

          if (stage.equals("Error"))
          {
              while (chars[i] != 30)
              {
                err += chars[i];
                i++;
              }

              if (err.equals("user"))
              {
                  ErrorDialog ed = new ErrorDialog(this.parent,true, "Could not connect: Wrong user");
                  ed.setVisible(true);
                  return false;
              }
              else if (err.equals("password"))
              {
                  ErrorDialog ed = new ErrorDialog(this.parent,true, "Could not connect: Wrong password");
                  ed.setVisible(true);
                  return false;
              }
          }
        }
        catch (IOException f) {
            ErrorDialog ed = new ErrorDialog(this.parent,true, "Cannot connect to the server");
            ed.setVisible(true);
            return false;
        }
        catch (Exception g) {
          //System.out.println("Exception: " + g);
            return false;
        }
        return true;
    }

    public void writeNewGame(String numberOfPlayers, String size)
    {
        try {
            BufferedOutputStream bos = new BufferedOutputStream(this.gameInfo.getSocket().getOutputStream());
          OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
          
          String process = "NewGame:" + (char) 13;
          osw.write(process);
          osw.flush();

          osw.write(numberOfPlayers + (char) 13);
          osw.flush();

          osw.write(size + (char) 13);
          osw.flush();

          }

        catch (IOException f) {
            //ErrorDialog ed = new ErrorDialog(this, true, "Cannot connect to the server");
            //ed.setVisible(true);
            System.out.println("IOException: " + f);
        }
        catch (Exception g) {
          System.out.println("Exception: " + g);
        }
    }

    public void writeJustLogin()
    {
        try {
          BufferedOutputStream bos = new BufferedOutputStream(this.gameInfo.getSocket().getOutputStream());
          OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

          String process = "JustLogin:" + (char) 13;
          osw.write(process);
          osw.flush();
          }

        catch (IOException f) {
            //ErrorDialog ed = new ErrorDialog(this, true, "Cannot connect to the server");
            //ed.setVisible(true);
            System.out.println("IOException: " + f);
        }
        catch (Exception g) {
          System.out.println("Exception: " + g);
        }
    }

    public void writeValue(int value) {
        try {
          BufferedOutputStream bos = new BufferedOutputStream(this.gameInfo.getSocket().getOutputStream());
          OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

          String process = String.valueOf(value) + (char) 13;
          osw.write(process);
          osw.flush();
        }
        catch (IOException f) {
            System.out.println("IOException: " + f);
        }
        catch(Exception e) {
            System.out.println("Exception: " + e);
        }
    }

    public int readValue() {
        return Integer.parseInt(this.readMessage());
    }
}


     






